package io.github.rascaler.dcenter.message;

import io.github.rascaler.dcenter.properties.CambrianExceptionProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * 从文件上加载
 * @ClassName MessageLoader
 * @Description TODO
 * @Author wurenqing
 * @Date 2022/7/5 9:48
 */
@Slf4j
public class PropertiesErrorMessageLoader implements ErrorMessageLoader {

    @Autowired
    private CambrianExceptionProperties cambrianExceptionProperties;

    @Override
    public Map<String, String> load() {
        Map<String, String> result = new HashMap<>();
        String[] locations = cambrianExceptionProperties.getLocations().split(",");
        for (String location : locations) {
            ClassPathResource resource = new ClassPathResource(location);
            if (!resource.exists()) {
                log.error("资源文件[{}]不存在", location);
                continue;
            }
            Properties p = new Properties();
            Map<String, String> map = new HashMap<>();
            try (InputStream is = resource.getInputStream()) {
                p.load(is);
                for(String e: p.stringPropertyNames()) {
                    map.put(e.trim(), p.getProperty(e.trim()));
                }
                // 检查重复
                List<String> list = map.keySet().stream().filter(it->result.keySet().contains(it)).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(list)) {
                    result.putAll(map);
                } else {
                    log.error(String.format("异常码定义重复,请检查,code=[%s]", String.join(",", list)));
                    throw new RuntimeException(String.format("异常码定义重复,请检查,code=[%s]", String.join(",", list)));
                }
            } catch (Exception e) {
                log.error(String.format("location=[%]无法加载", location));
                throw new RuntimeException(String.format("location=[%]无法加载", location));
            }
        }
        return result;
    }


}
